package org.darkforest.admin.controller;

import org.darkforest.common.services.ProxyManagerService;
import org.darkforest.common.util.Page;
import org.darkforest.common.util.Utils;
import org.darkforest.dao.mapper.*;
import org.darkforest.enums.ProxyApplyStageEnum;
import org.darkforest.model.*;
import org.darkforest.ucenter.auth.AuthPassport;
import org.darkforest.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by valentina on 15/5/11.
 * 代理商控制类
 */
@Controller
@RequestMapping("proxy")
public class ProxyController {

    @Autowired
    private ProxyMapper proxyMapper;
    @Autowired
    private ProxyManagerService proxyService;
    @Autowired
    private BrandMapper brandMapper;
    @Autowired
    private ProxyGoodsMapper proxyGoodsMapper;
    @Autowired
    private GoodsCommonMapper goodsCommonMapper;
    @Autowired
    private HelpMapper helpMapper;
    @Autowired
    private HelpTypeMapper helpTypeMapper;
    @Autowired
    private SettingMapper settingMapperr;
    @Autowired
    private ProxyManagerService proxyManagerService;

    @AuthPassport
    @RequestMapping("proxyList")
    public ModelAndView proxyList(Integer page,String contactName,Integer proxyId,HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView("proxy/proxy_list");
        Proxy proxy = new Proxy();
        proxy.setStart(page == null ? 1 : page);
        proxy.setPageSize(Page.DEFAULT_PAGE_SIZE);
        proxy.setProxyId(proxyId);
        proxy.setContactName(contactName==null?"":contactName);
//        proxy.setApproveResult(0);

        List<Proxy> proxyList = proxyMapper.findProxyByCondition(proxy);
        proxy.setResultList(proxyList);
        modelAndView.addObject("modelPage", proxy);
        return modelAndView;
    }
    @RequestMapping("toApproveProxy")
    public ModelAndView toApproveProxy(Integer proxyId) {
        ModelAndView modelAndView = new ModelAndView("proxy/approve_proxy");
        ProxyApproveVO proxyApproveVO = proxyService.ApproveProxyDetail(proxyId);
        modelAndView.addObject("proxyApproveVO", proxyApproveVO);
        return modelAndView;
    }

    @AuthPassport
    @RequestMapping("doApproveProxy")
    public String doApproveProxy(Integer memberId,Integer proxyId,Integer teamId, Integer result, HttpSession session) {
        MemberBase adminInfo = (MemberBase)session.getAttribute("memInfo");

        ModelAndView modelAndView = null;
        Proxy proxy = new Proxy();
        proxy.setProxyId(proxyId);
        proxy.setApprover(adminInfo.getUserName());
        proxy.setApproveDate(new Date());
        proxy.setApproveResult(result);
        proxy.setApplyStage(ProxyApplyStageEnum.COMPLETE);
        //全部放在service中处理，绑定事务
        proxyManagerService.aduitProxy(memberId,proxy);
        switch (result) {
            case 1:
                return "redirect: toAddProxyGoods?teamId=" + teamId;
            case 2:
                return "msg";
            default:
                modelAndView = new ModelAndView("msg");
                modelAndView.addObject("msg", "审核操作失败");
                return "msg";
        }
    }

    @AuthPassport
    @RequestMapping("toAddProxyGoods")
    public ModelAndView toAddProxyGoods(Integer page, Integer teamId) {
        ModelAndView modelAndView = new ModelAndView("proxy/add_approve_goods");

        GoodsCommonPage modelPage = new GoodsCommonPage(page == null ? 1 : page, Page.DEFAULT_PAGE_SIZE);
        List<GoodsCommonProxyVO> goodsCommonProxyVOList = this.goodsCommonMapper.findProxyGoodsByPage(modelPage);


        ProxyGoods proxyGoods = new ProxyGoods();
        proxyGoods.setProxyId(teamId);
        List<ProxyGoods> approveProxyList = this.proxyGoodsMapper.findProxyGoodsByCondition(proxyGoods);


        for(GoodsCommonProxyVO goodsCommonProxyVO:goodsCommonProxyVOList){
            for(ProxyGoods proxyGoods1:approveProxyList){
                if(goodsCommonProxyVO.getGoodsCommonid().equals(proxyGoods1.getGoodsCommonId())){
                    goodsCommonProxyVO.setFlag(true);
                }
            }
        }



        List<Brand> brandList = this.brandMapper.findBrandByCondition(new Brand());
        modelPage.setResultList(goodsCommonProxyVOList);

        modelAndView.addObject("approveProxyList", approveProxyList);
        modelAndView.addObject("modelPage", modelPage);
        modelAndView.addObject("brandList", brandList);
//        modelAndView.addObject("goodsCommonId", goodsCommonId);
        modelAndView.addObject("teamId", teamId);
        return modelAndView;
    }

    @RequestMapping("doAddProxyGoods")
    public @ResponseBody
    AjaxReturnData doAddProxyGoods(Integer proxyId, Integer goodsCommonId, String goodsName, String goodsPrice, String goodsImg) {

        ProxyGoods proxyGoods = new ProxyGoods();
        proxyGoods.setProxyId(proxyId);
        proxyGoods.setGoodsImage(goodsImg);
        proxyGoods.setGoodsCommonId(goodsCommonId);
        proxyGoods.setGoodsCommonName(encodeStr(goodsName));
        proxyGoods.setGoodsPrice(new BigDecimal(goodsPrice));
        AjaxReturnData ajaxReturnData = new AjaxReturnData();
        int i = proxyGoodsMapper.insertProxyGoods(proxyGoods);
        if (i > 0){
            ajaxReturnData.setType("true");
            ajaxReturnData.setMessage("为审核已通过的代理商添加代理商品成功");
        } else{
            ajaxReturnData.setType("false");
            ajaxReturnData.setMessage("为审核已通过的代理商添加代理商品失败");

        }
        return ajaxReturnData;
    }


    @RequestMapping("delProxyGoods")
    public @ResponseBody AjaxReturnData delProxyGoods(Integer proxyId,Integer goodsCommonId ){
        AjaxReturnData ajaxReturnData = new AjaxReturnData();

        ProxyGoods proxyGoods = new ProxyGoods();
        proxyGoods.setProxyId(proxyId);
        proxyGoods.setGoodsCommonId(goodsCommonId);

        int i = proxyGoodsMapper.deleteByGoodsProxy(proxyGoods);

        if(i>0){
            ajaxReturnData.setType("true");
            ajaxReturnData.setMessage("为审核已通过的代理商删除代理商品成功");
        }else{
            ajaxReturnData.setType("false");
            ajaxReturnData.setMessage("为审核已通过的代理商删除代理商品失败");
        }
        return ajaxReturnData;

    }



    @RequestMapping("toAddProxyGoodsSearch")
    public ModelAndView SearchGoodsCommonProxy(Integer page, HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView("proxy/add_approve_goods");
        GoodsCommonPage modelPage = new GoodsCommonPage(page == null ? 1 : page, Page.DEFAULT_PAGE_SIZE);
        String goodsName = request.getParameter("goodsName");
        String storeName = request.getParameter("storeName");
        String brandId = request.getParameter("brandId");
        String goodsSerial = request.getParameter("goodsSerial");
        if (Utils.isNotEmpty(goodsName)) {
            modelPage.setGoodsName(encodeStr(goodsName));
            modelAndView.addObject("goodsName", encodeStr(goodsName));
        }
        if (Utils.isNotEmpty(storeName)) {
            modelPage.setStoreName(encodeStr(storeName));
            modelAndView.addObject("storeName", encodeStr(storeName));
        }
        if (Utils.isNotEmpty(brandId)) {
            modelPage.setBrandId(Integer.parseInt(brandId));
        }
        if (Utils.isNotEmpty(goodsSerial)) {
            modelPage.setGoodsSerial(encodeStr(goodsSerial));
            modelAndView.addObject("goodsSerial", encodeStr(goodsSerial));
        }
        List<GoodsCommonProxyVO> goodsCommonProxyVOList = this.goodsCommonMapper.searchGoodsForProxy(modelPage);
        List<Brand> brandList = this.brandMapper.findBrandByCondition(new Brand());
        modelPage.setResultList(goodsCommonProxyVOList);

        modelAndView.addObject("modelPage", modelPage);
        modelAndView.addObject("brandList", brandList);
        return modelAndView;
    }
    /**
     * 字符编码格式化UTF-8
     *
     * @param str
     * @return
     */
    public static String encodeStr(String str) {
        try {
            return new String(str.getBytes("ISO-8859-1"), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }
    }
    @RequestMapping("proxyHelp")
    public ModelAndView proxyHelp(Integer page, HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView("proxy/proxy_help_list");
        List<Help> helps = helpMapper.findProxyHelpByCondition(new Help());
        modelAndView.addObject("helps", helps);
        List<HelpType> helpTypes = helpTypeMapper.findProxyHelpClassByCondition(new HelpType());
        modelAndView.addObject("helpTypes", helpTypes);
        return modelAndView;
    }
    /**
     * 高级查询帮助文档
     * @return
     */
    @RequestMapping("proxyHelp/searchProxyHelp")
    public ModelAndView searchBrand(HttpServletRequest request){
        String helpTitle = request.getParameter("helpTitle");
        String typeId = request.getParameter("typeId");
        Help help = new Help();
        if(helpTitle!= null &&!helpTitle.equals("")){
            help.setHelpTitle(helpTitle);
        }
        if(typeId!= null &&!typeId.equals("")){
            help.setTypeId(Integer.parseInt(typeId));
        }
        ModelAndView modelAndView =new ModelAndView("proxy/proxy_help_list");
        List<Help> helps = helpMapper.findProxyHelpByCondition(new Help());
        modelAndView.addObject("helps", helps);
        modelAndView.addObject("helpTitle",helpTitle);
        modelAndView.addObject("typeId",typeId);
        List<HelpType> helpTypes = helpTypeMapper.findProxyHelpClassByCondition(new HelpType());
        modelAndView.addObject("helpTypes", helpTypes);
        return modelAndView;
    }
    @RequestMapping("proxyHelp/toAdd")
    public ModelAndView toProxyHelpAdd() {
        ModelAndView modelAndView = new ModelAndView("proxy/proxy_help_add");
        List<HelpType> helpTypes = helpTypeMapper.findProxyHelpClassByCondition(new HelpType());
        modelAndView.addObject("helpTypes", helpTypes);
        return modelAndView;
    }
    /**
     * 插入帮助文挡
     * @return
     */
    @RequestMapping("proxyHelp/doProxyHelpAdd")
    public ModelAndView doProxyHelpAdd(MultipartHttpServletRequest multipartHttpServletRequest){
        ModelAndView modelAndView = new ModelAndView("msg");
        Help help = new Help();
        help.setHelpSort(Integer.parseInt(multipartHttpServletRequest.getParameter("helpSort")));
        help.setTypeId(Integer.parseInt(multipartHttpServletRequest.getParameter("typeId")));
        help.setHelpTitle(multipartHttpServletRequest.getParameter("helpTitle"));
        help.setHelpUrl(multipartHttpServletRequest.getParameter("helpUrl"));
        help.setHelpInfo(multipartHttpServletRequest.getParameter("content"));
        help.setUpdateTime((int) System.currentTimeMillis());
        String[] pictures = multipartHttpServletRequest.getParameterValues("picture");
        String picture = null;
        if(pictures!=null && (pictures.length > 0)){
            for(int i=0;i<pictures.length;i++){
                if(i==0){
                    picture = pictures[i];
                }else{
                    picture += ","+ pictures[i];
                }
            }
        }
        help.setPicture(picture);
        int i = helpMapper.insert(help);
        if(i>0){
            modelAndView.addObject("msg","帮助内容新增成功");
        }else{
            modelAndView.addObject("msg","帮助内容新增失败");
        }
        return modelAndView;
    }

    @RequestMapping("proxyHelp/toProxyHelpModify")
    public ModelAndView toProxyHelpModify(Integer helpId){
        ModelAndView modelAndView = new ModelAndView("proxy/proxy_help_modify");
        Help help = this.helpMapper.selectByPrimaryKey(helpId);
        modelAndView.addObject("help",help);
        List<HelpType> helpTypes = helpTypeMapper.findProxyHelpClassByCondition(new HelpType());
        modelAndView.addObject("helpTypes", helpTypes);
        if(help.getPicture()!=null){
            List <String> pictures = new ArrayList<String>();
            for(int i=0;i<help.getPicture().split(",").length;i++){
                pictures.add(help.getPicture().split(",")[i]);
            }
            modelAndView.addObject("pictures",pictures);
        }
        return modelAndView;
    }
    @RequestMapping("proxyHelp/toProxyHelpForGuideModify")
    public ModelAndView toProxyHelpForGuideModify(Integer helpId){
        ModelAndView modelAndView = new ModelAndView("proxy/proxy_entry_guide_modify");
        Help help = this.helpMapper.selectByPrimaryKey(helpId);
        modelAndView.addObject("help",help);
        if(help.getPicture()!=null){
            List <String> pictures = new ArrayList<String>();
            for(int i=0;i<help.getPicture().split(",").length;i++){
                pictures.add(help.getPicture().split(",")[i]);
            }
            modelAndView.addObject("pictures",pictures);
        }
        return modelAndView;
    }
    /**
     * 修改帮助文挡
     * @return
     */
    @RequestMapping("proxyHelp/doProxyHelpModify")
    public ModelAndView doProxyHelpModify(MultipartHttpServletRequest multipartHttpServletRequest){
        ModelAndView modelAndView = new ModelAndView("msg");
        Help help = new Help();
        help.setHelpSort(Integer.parseInt(multipartHttpServletRequest.getParameter("helpSort")));
        help.setTypeId(Integer.parseInt(multipartHttpServletRequest.getParameter("typeId")));
        help.setHelpTitle(multipartHttpServletRequest.getParameter("helpTitle"));
        help.setHelpUrl(multipartHttpServletRequest.getParameter("helpUrl"));
        help.setHelpInfo(multipartHttpServletRequest.getParameter("content"));
        help.setHelpId(Integer.parseInt(multipartHttpServletRequest.getParameter("helpId")));
        help.setUpdateTime((int) System.currentTimeMillis());
        String[] pictures = multipartHttpServletRequest.getParameterValues("picture");
        String picture = null;
        if(pictures!=null && pictures.length>0){
            for(int i=0;i<pictures.length;i++){
                if(i==0){
                    picture = pictures[i];
                }else{
                    picture += ","+ pictures[i];
                }
            }
        }
        help.setPicture(picture);
        int i = helpMapper.updateByPrimaryKey(help);
        if(i>0){
            modelAndView.addObject("msg","帮助类型修改成功");
        }else{
            modelAndView.addObject("msg","帮助类型修改失败");
        }
        return modelAndView;
    }
    @RequestMapping("proxyHelp/toProxyHelpDelete")
    public  ModelAndView toProxyHelpDelete(HttpServletRequest request){
        String[] helpId = request.getParameterValues("helpId");
        int i=0;
        for(String id :helpId ){
            i+= helpMapper.deleteByPrimaryKey(Integer.parseInt(id));
        }
        ModelAndView modelAndView = new ModelAndView("msg");
        if(i==helpId.length){
            modelAndView.addObject("msg","帮助内容删除成功");
        }else{
            modelAndView.addObject("msg","帮助内容删除失败");
        }
        return modelAndView;
    }
    @RequestMapping("proxyHelp/proxyHelpClass")
    public ModelAndView proxyHelpClass(Integer page, HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView("proxy/proxy_help_class_list");
        List<HelpType> helpTypes = helpTypeMapper.findProxyHelpClassByCondition(new HelpType());
        modelAndView.addObject("helpTypes", helpTypes);
        return modelAndView;
    }
    @RequestMapping("proxyHelp/toProxyHelpClassAdd")
    public ModelAndView toProxyHelpClass() {
        ModelAndView modelAndView = new ModelAndView("proxy/proxy_help_class_add");
        return modelAndView;
    }
    @RequestMapping("proxyHelp/doProxyHelpClassAdd")
    public ModelAndView doProxyHelpClassAdd(MultipartHttpServletRequest multipartHttpServletRequest){
        ModelAndView modelAndView = new ModelAndView("msg");
        HelpType helpType = new HelpType();
        helpType.setTypeName(multipartHttpServletRequest.getParameter("typeName"));
        helpType.setTypeSort(Integer.parseInt(multipartHttpServletRequest.getParameter("typeSort")));
        helpType.setHelpCode(multipartHttpServletRequest.getParameter("helpCode"));
        helpType.setHelpShow("0".equals(multipartHttpServletRequest.getParameter("helpShow")) ? true : false);
        helpType.setTypeClass(1);
        int i = helpTypeMapper.insert(helpType);
        if(i>0){
            modelAndView.addObject("msg","帮助类型新增成功");
        }else{
            modelAndView.addObject("msg","帮助类型新增失败");
        }
        return modelAndView;
    }
    @RequestMapping("proxyHelp/toProxyHelpClassModify")
    public ModelAndView toProxyHelpClassModify(Integer typeId){
        ModelAndView modelAndView = new ModelAndView("proxy/proxy_help_class_modify");
        HelpType helpType = this.helpTypeMapper.selectByPrimaryKey(typeId);
        modelAndView.addObject("helpType",helpType);
        return modelAndView;
    }
    @RequestMapping("proxyHelp/doProxyHelpClassModify")
    public ModelAndView doProxyHelpClassModify(MultipartHttpServletRequest multipartHttpServletRequest){
        ModelAndView modelAndView = new ModelAndView("msg");
        HelpType helpType = new HelpType();
        helpType.setTypeName(multipartHttpServletRequest.getParameter("typeName"));
        helpType.setTypeSort(Integer.parseInt(multipartHttpServletRequest.getParameter("typeSort")));
        helpType.setHelpCode(multipartHttpServletRequest.getParameter("helpCode"));
        helpType.setHelpShow("0".equals(multipartHttpServletRequest.getParameter("helpShow")) ? true : false);
        helpType.setTypeId(Integer.parseInt(multipartHttpServletRequest.getParameter("typeId")));
        int i = helpTypeMapper.updateByPrimaryKey(helpType);
        if(i>0){
            modelAndView.addObject("msg","帮助类型修改成功");
        }else{
            modelAndView.addObject("msg","帮助类型修改失败");
        }
        return modelAndView;
    }

    @RequestMapping("proxyHelp/toProxyHelpClassDelete")
    public  ModelAndView delArticleClass(HttpServletRequest request){
        String[] typeIds = request.getParameterValues("typeId");
        int i=0;
        for(String id :typeIds ){
            i+= helpTypeMapper.deleteByPrimaryKey(Integer.parseInt(id));
        }
        ModelAndView modelAndView = new ModelAndView("msg");
        if(i==typeIds.length){
            modelAndView.addObject("msg","帮助类型删除成功");
        }else{
            modelAndView.addObject("msg","帮助类型删除失败");
        }
        return modelAndView;
    }

    @RequestMapping("proxyHome")
    public ModelAndView proxyHome(Integer page, HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView("proxy/proxy_home");
        return modelAndView;
    }
    @RequestMapping("proxyHome/doProxyHomeAdd")
    public ModelAndView doProxyHomeAdd(HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView("msg");
        Setting setting = new Setting();
        String[] pictures =  request.getParameterValues("picture");
        String picture = null;
        if(pictures!=null && pictures.length>0){
            for(int i=0;i<pictures.length;i++){
                if(picture==null){
                    if(!"".equals(pictures[i])){
                        picture = pictures[i];
                    }
                }else{
                    if(!"".equals(pictures[i])){
                        picture += ","+ pictures[i];
                    }
                }
            }
        }
        System.out.print(picture);
        setting.setName("proxy_joinin_pic");
        setting.setValue(picture);
        int i = settingMapperr.updateByPrimaryKeyWithBLOBs(setting);
        if(i>0){
            setting.setName("proxy_joinin_hint");
            setting.setValue(request.getParameter("show_txt"));
            int j = settingMapperr.updateByPrimaryKeyWithBLOBs(setting);
            if(j>0){
                modelAndView.addObject("msg","图片提示修改成功");
            }else{
                modelAndView.addObject("msg","图片提示修改失败");
            }
        } else {
            modelAndView.addObject("msg","图片提示修改失败");
        }
        return modelAndView;
    }
    @RequestMapping("proxyHome/entryGuide")
    public ModelAndView proxyEntryGuide(Integer page, HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView("proxy/proxy_entry_guide");
        Help help = new Help();
        help.setTypeId(1);//入住指南类型为1
        List<Help> helps = helpMapper.findProxyHelpByCondition(help);
        modelAndView.addObject("helps", helps);
        return modelAndView;
    }
}
